package edu.uwm.universitydb.controller;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.SwingUtilities;


import edu.uwm.universitydb.swing.PerformanceTableModel;
import edu.uwm.universitydb.swing.ProgressGlassPane;
import edu.uwm.universitydb.tests.PerformanceTests;
import edu.uwm.universitydb.view.Main;
import edu.uwm.universitydb.view.PerformanceMaint;

public class PerformanceMaintController implements MouseListener {
	
	public PerformanceMaintController(Main main) {
		_perfTests = new PerformanceTests();
		// Create our associated view
		_parent = main;
		_view = new PerformanceMaint(new PerformanceTableModel(_perfTests));
		
		_glassPane =  new ProgressGlassPane();
		_parent.getFrame().setGlassPane(_glassPane);
		// Setup our listeners
		_view.getRunButton().addMouseListener(this);
	}

  
	private void onRunButtonClick() {

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				_view.getRunButton().setEnabled(false);
				_parent.getFrame().setEnabled(false);
				_glassPane.start();
				Thread tests = new Thread(new Runnable() {
					public void run() {
						// Run Tests update progress
						_glassPane.setProgress(0);
						_perfTests.runQuery(0);
						_glassPane.setProgress(20);
						_perfTests.runQuery(1);
						_glassPane.setProgress(40);
						_perfTests.runQuery(2);
						_glassPane.setProgress(60);
						_perfTests.runQuery(3);
						_glassPane.setProgress(80);
						_perfTests.runQuery(4);
						_glassPane.stop();
						_parent.getFrame().setEnabled(true);
						_view.getRunButton().setEnabled(true);
						_view.refreshTable();
					}
				});
				tests.start();
			}
		});
	}
	
	public PerformanceMaint getView() {
		return _view;
	}
	
	
	@Override
	public void mouseClicked(MouseEvent e) {
		//Based on the element clicked, fire off appropriate handler method.
		switch(e.getComponent().getName()) {
			case PerformanceMaint.RUNBUTTON: 
				this.onRunButtonClick();
				break;
			default: 
				//Not sure what they clicked, do nothing
				break;
		}
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// Unused		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// Unused
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// Unused
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// Unused
	}	
	

	private PerformanceMaint _view;
	
	private PerformanceTests _perfTests;
	
	private ProgressGlassPane _glassPane;
	
	private Main _parent;

	public static final String ID = "PrfMnt";

}
